package com.jky.stmall.front.controller;

import com.jky.stmall.front.entity.User;
import com.jky.stmall.front.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
@AllArgsConstructor
public class UserController {
    //构造方法注入
    private UserService userService;

    //用户注册的页面
    @GetMapping("/reg")
    public String reg() {
        return "/user/reg";
    }

    //就扼守注册请求
    @PostMapping("/reg")
    public String reg(String username, String password, @RequestParam("repassword") String rePassword, Model model) {
    //调用Service层，完成用户注册
        try {
            userService.reg(username,password,rePassword);
            //注册成功 跳转到登陆页面
            return "redirect:/user/login";

        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error",e.getMessage());
            return "user/reg";
        }

    }
    /*
     * 处理器方法的参数上有三种注解。
     * 1.@RequsetParam ：客户端参数名与服务端参数名不一致
     * 2.@RequestBody ：用来接收客户端传递的JSON格式的数据，解析JSON注入参数中
     * 3.@PathVariable： RESTful 路径参数
     * */
    //登陆页面
    @GetMapping("/login")
    public String login(){
        return "user/login";
    }
    //登陆的处理
    @PostMapping("/login")
    public String login(User user, HttpSession session,Model model){
        try {
            user  = userService.login(user);
            //登陆成功
            session.setAttribute("user",user);
            //跳转到主页
            return "redirect:/";
        } catch (Exception e) {
            e.printStackTrace();
            model.addAttribute("error",e.getMessage());
            return "user/login";
        }
    }
    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/";
    }
}
